import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'

interface AppStore {
  // 用户认证
  jwt: string
  nickName: string
  avatar: string
  userId: string | null
  
  // 应用状态
  menus: any[]
  permissions: string[]
  
  // 方法
  isLogin: () => boolean
  setLogin: (jwt: string, nickName: string, avatar?: string, userId?: string) => void
  logOut: () => void
  setMenus: (menus: any[]) => void
  setPermissions: (permissions: string[]) => void
}

export const useAppStore = create<AppStore>()(
  persist(
    immer((set, get) => ({
      // 初始状态
      jwt: '',
      nickName: '',
      avatar: '',
      userId: null,
      menus: [],
      permissions: [],
      
      // 方法实现
      isLogin: () => {
        const state = get()
        return !!state.jwt && !!state.nickName
      },
      
      setLogin: (jwt, nickName, avatar = '', userId = '') => {
        set((state) => {
          state.jwt = jwt
          state.nickName = nickName
          state.avatar = avatar
          state.userId = userId
        })
      },
      
      logOut: () => {
        set((state) => {
          state.jwt = ''
          state.nickName = ''
          state.avatar = ''
          state.userId = null
          state.menus = []
          state.permissions = []
        })
      },
      
      setMenus: (menus) => {
        set((state) => {
          state.menus = menus
        })
      },
      
      setPermissions: (permissions) => {
        set((state) => {
          state.permissions = permissions
        })
      },
    })),
    {
      name: 'aiadmin-store',
      storage: createJSONStorage(() => localStorage),
    }
  )
)